# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .models import SipPro
import os
import xadmin
from .MyIO import *
from .ConnFreeswitch import *
from django import forms
from .MySqlite import *
from django.http import Http404, HttpResponseRedirect

config_file_patch = "/usr/local/freeswitch/conf/"
getcwd="/var/www/MyIPPbx"

class PublicExtensionAdmin(object):
    list_display = ['name', 'number', 'transfer']
    list_per_page = 10
    add_form_template = 'myform.html'
    change_form_template = 'myform.html'
    xadmin.views.edit.UpdateAdminView.exclude = ['name']

    def save_models(self):
        obj = self.new_obj
        self.new_obj.save()
        dinfo = ReadFile(os.path.join(getcwd + "/pbx/tpl", 'Public_Extension.xml'))
        dinfo = dinfo.replace('{name}', obj.name)
        dinfo = dinfo.replace('{number}', obj.number)
        dinfo = dinfo.replace('{transfer}', obj.transfer)
        dialplan = ReadFile(config_file_patch + "dialplan/public.xml")
        urllist = str(self.request.get_full_path()).split('/')
        if len(urllist) == 5:
            dialplan = dialplan.replace("<!-- a public Extensions  -->", "<!-- a public Extensions  -->\r\n" + dinfo)
        else:
            myivr = ReadFile(os.path.join(getcwd + "/pbx/tpl", 'pubExt_' + obj.name + '.xml'))
            dialplan = dialplan.replace(myivr, dinfo)
        WriteFile(config_file_patch + "dialplan/public.xml", dialplan)
        WriteFile(os.path.join(getcwd + "/pbx/tpl", 'pubExt_' + obj.name + '.xml'), dinfo)
        r = ReloadXml()
        if r == -1:
            self.message_user(u'告警,IPPBX加载失败，请重启IPPBX或者手动加载!', 'warning')

    def delete_models(self, obj):
        dialplan = ReadFile(config_file_patch + "dialplan/public.xml")
        for vars in obj:
            dinfo = ReadFile(os.path.join(getcwd + "/pbx/tpl", 'pubExt_' + str(vars) + '.xml'))
            print dinfo
            dialplan = dialplan.replace("\r\n" + dinfo, "")
            WriteFile(config_file_patch + "dialplan/public.xml", dialplan)
        deleteFileIvr("pubExt_", obj, getcwd + "/pbx/tpl/", ".xml")
        r = ReloadXml()
        if r == -1:
            self.message_user(u'告警,IPPBX加载失败，请重启IPPBX或者手动加载!', 'warning')
        obj.delete()